//   Copyright (c) [2023] [423109070325付志峰]
//   [春天的高等数学代码库] is licensed under Mulan PSL v2.
//   You can use this software according to the terms and conditions of the Mulan PSL v2. 
//   You may obtain a copy of Mulan PSL v2 at:
//            http://license.coscl.org.cn/MulanPSL2 
//   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
//   See the Mulan PSL v2 for more details. 
//求根公式 
#include <stdio.h>
// 使用开根号 sqrt(d) 函数时，需要添加此头文件
#include <math.h>
 
int main()
{

 
    float a , b , c, d, x1, x2;
 
    printf("请依次输入三个系数: ");
    scanf("%f %f %f", &a,&b,&c);
 
    if(a != 0)
    {
        d = b * b - 4 * a * c;                        // 根的判别式
        if(d >= 0)
        {
            x1 = ((-b + sqrt(d)) / (2 * a));            // 求根公式
            x2 = ((-b - sqrt(d)) / (2 * a));
 
            printf("x1 = %.2f;x2 = %.2f", x1, x2);
        }
        else
        {
            printf("方程无根");
        }
    }
    else
    {
        printf("输入的第一个值不合法，请重新输入！");
    }
 
 
    return 0;
}


//牛顿迭代法 
#include <stdio.h>
#include <math.h>

float solution(float a, float b, float c, float d)
{
	float x0, f, fd, h; 
	float x = 1.5;

	do
	{
		x0 = x; 

		f = a * x0 * x0 * x0 + b * x0 * x0 + c * x0 + d;

		fd = 3 * a * x0 * x0 + 2 * b * x0 + c;

		h = f / fd;

		x = x0 - h; 

	} while (fabs(x-x0) >= 1e-5);

	return x;
}

int main()
{
	float a, b, c, d; 

	float x; 
	
	printf("请输入方程的系数：");
	
	scanf("%f %f %f %f", &a, &b, &c, &d);
	
	x = solution(a, b, c, d);
	
	printf("\n");
	
	printf("所求方程的根为：x=%f\n", x);

	return 0;
}


//二分法 

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
double f(double x)
{
    return (x*x*x-3*x*x+3*x-1);
}
int main()
{
    double x1,x2,xx;//x1,x2代表区间左右边界，xx代表方程跟的值
    do
    {
        scanf("%lf%lf",&x1,&x2);
    }
    while(f(x1)*f(x2)>0);//保证f(x1)和f(x2)是异号，这样才可以进行下一步的精准区间，否则，重新输入x1，x2的值
    do
    {
        xx=(x1+x2)/2;
        if(f(xx)*f(x1)>0)
            x1=xx;
        else
            x2=xx;
    }
    while(fabs(f(xx))>=1e-7);//le-6代表1*10的-6次方，它的值将影响到跟的准确度的问题
    printf("%.2lf\n",xx);
    return 0;
}

    
